import math, json, datetime
from http.client import HTTPException

from django.http import HttpResponse

from user_app.models import AccountInfo
from utils.error_code import ServiceFailure


def format_filesize(size):
    if (size < 1024):
        return '%s B' % size
    size = size / 1024.0
    size_name = ("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    i = int(math.floor(math.log(size, 1024)))
    p = math.pow(1024, i)
    s = round(size / p, 2)
    return '%s %s' % (s, size_name[i])


def json_response(result: dict, status=200):
    return HttpResponse(json.dumps(result, cls=CommonJsonEncoder), status=status,  content_type='application/json')


class AccountManager:
    """
        AccountInfo类级缓存
    """

    def __init__(self):
        self.account_dict = {}

    def get_account_by_id(self, account_id):
        if account_id in self.account_dict:
            return self.account_dict[account_id]
        else:
            return self.set_account_by_id(account_id)

    def set_account_by_id(self, account_id):
        if account_id not in self.account_dict:
            account = AccountInfo.objects.filter(id=account_id)
            if account:
                self.account_dict[account[0].id] = account[0]
                return account[0]



class Pagination(object):

    def __init__(self, page, per_page, total):
        self.page = page
        self.per_page = per_page
        self.total = total

    @property
    def pages(self):
        return int(math.ceil(self.total / float(self.per_page)))

    @property
    def offset(self):
        return (self.page - 1) * self.per_page

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages

    @property
    def dict(self):
        return {'page': self.page, 'pages': self.pages, 'per_page': self.per_page, 'total': self.total}

    @property
    def json(self):
        return json.dumps(self.dict)

    def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2):
        last = 0
        for num in range(1, self.pages + 1):
            if num <= left_edge or (
                    self.page - left_current - 1 < num < self.page + right_current) or num > self.pages - right_edge:
                if last + 1 != num:
                    yield None
                yield num
                last = num

    def __repr__(self):
        return '<Pagination: %d/%d,%d/%d>' % (self.page, self.pages, self.per_page, self.total)


class CommonJsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime("%Y-%m-%d")
        return json.JSONEncoder.default(self, o)
